package com.bw.gmall.realtime.dws.app;

import cn.hutool.core.collection.ListUtil;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradePaymentBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.DorisMapFunction;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.ArrayList;

/**
 * @projectName: gmalll2206
 * @package: com.bw.gmall.realtime.dws.app
 * @className: DwsTradePaymentSucWindow
 * @author: DuanYu
 * @description: TODO
 * @date: 2025/3/5 11:25
 * @version: 1.0
 */

public class DwsTradePaymentSucWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradePaymentSucWindow().start(Constant.TOPIC_DWD_TRADE_ORDER_PAYMENT_SUCCESS, Constant.DWS_TRADE_PAYMENT_SUC_WINDOW, 4, 10027);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        SingleOutputStreamOperator<JSONObject> etlStream = getEtlStream(dataStreamSource);
//        etlStream.print();
        SingleOutputStreamOperator<JSONObject> wmStream = getWmStream(etlStream);
        KeyedStream<JSONObject, String> keyedStream = getKeyedStream(wmStream);
//        keyedStream.print();
        SingleOutputStreamOperator<TradePaymentBean> process = getProcess(keyedStream);
//        process.print();
        SingleOutputStreamOperator<TradePaymentBean> result = getResult(process);
        result.print();
        //result.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_PAYMENT_SUC_WINDOW));

    }


    private static SingleOutputStreamOperator<TradePaymentBean> getResult(SingleOutputStreamOperator<TradePaymentBean> process) {
        return process.windowAll(TumblingEventTimeWindows.of(Time.seconds(5))).process(new ProcessAllWindowFunction<TradePaymentBean, TradePaymentBean, TimeWindow>() {
            @Override
            public void process(ProcessAllWindowFunction<TradePaymentBean, TradePaymentBean, TimeWindow>.Context context, Iterable<TradePaymentBean> iterable, Collector<TradePaymentBean> collector) throws Exception {
                ArrayList<TradePaymentBean> tradePaymentBeanArrayList = ListUtil.toList(iterable);
                long snc = tradePaymentBeanArrayList.stream().mapToLong(e -> e.getPaymentSucNewUserCount()).sum();
                long suc = tradePaymentBeanArrayList.stream().mapToLong(e -> e.getPaymentSucUniqueUserCount()).sum();
                String start = DateFormatUtil.tsToDateTime(context.window().getStart());
                String end = DateFormatUtil.tsToDateTime(context.window().getEnd());
                String curDate = DateFormatUtil.tsToDate(System.currentTimeMillis());
                TradePaymentBean next = tradePaymentBeanArrayList.iterator().next();
                collector.collect(TradePaymentBean.builder().stt(start)
                        .edt(end)
                        .curDate(curDate)
                        .paymentSucUniqueUserCount(suc)
                        .paymentSucNewUserCount(snc)
                        .ts(next.getTs())
                        .build());
            }
        });
    }

    private static SingleOutputStreamOperator<TradePaymentBean> getProcess (KeyedStream<JSONObject, String> keyedStream) {
         return keyedStream.process(new KeyedProcessFunction<String, JSONObject, TradePaymentBean>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("success", String.class);
                valueState = getRuntimeContext().getState(valueStateDescriptor);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradePaymentBean>.Context context, Collector<TradePaymentBean> collector) throws Exception {
                Long ts = jsonObject.getLong("ts") * 1000;
                String dateTime = DateFormatUtil.tsToDate(ts);
                String value = valueState.value();
                long payUuCount = 0L;
                long payNewCount = 0L;
                if (!dateTime.equals(value)) {
                    payUuCount = 1L;
                    valueState.update(dateTime);
                    if (value == null) {
                        payNewCount = 1L;
                    }
                }
                if (payUuCount == 1) {
                    collector.collect(TradePaymentBean.builder().ts(ts).paymentSucUniqueUserCount(payUuCount).paymentSucNewUserCount(payNewCount).build());
                }
            }
        });
    }

    private static KeyedStream<JSONObject, String> getKeyedStream(SingleOutputStreamOperator<JSONObject> wmStream) {
        return wmStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("user_id");
            }
        });
    }

    private static SingleOutputStreamOperator<JSONObject> getWmStream(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts")*1000;
            }
        }));
    }

    private static SingleOutputStreamOperator<JSONObject> getEtlStream(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                if (s != null) {
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String user_id = jsonObject.getString("user_id");
                    if (!StringUtils.isEmpty(user_id)) {
                        collector.collect(jsonObject);
                    }
                }
            }
        });
    }
}
